/**
 *
 */
package name.yzhu.wbdata.io;

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import name.yzhu.common.Constant;
import name.yzhu.common.io.BinaryFileReader;
import name.yzhu.common.io.FileIndexEntry;
import name.yzhu.common.util.IdentifyUnique;

/**
 * @author yhzhu
 *
 */
public class PersistIdentifyUnique implements IdentifyUnique {
	private static final Log LOG = LogFactory.getLog(PersistIdentifyUnique.class);
	private ConcurrentMap<String, Object> map =
		new ConcurrentHashMap<String, Object>();

	private File file = null;

	public PersistIdentifyUnique(String path) {
		this(new File(path));
	}

	public PersistIdentifyUnique(final File file) {
		this.file  = file;
	}

	/* (non-Javadoc)
	 * @see name.yzhu.common.util.IdentifyUnique#open()
	 */
	@Override
	public void open() throws Exception {
		BinaryFileReader reader = null;
		try {
			reader = new BinaryFileReader();
			reader.open(file.getAbsolutePath()+Constant.IDX_FILE_SUFFIX_NAEM);
			FileIndexEntry idx = new FileIndexEntry();
			while (reader.read(idx)) {
				map.put(idx.getId(), 1);
			}
		} catch (Exception e) {
			LOG.error("open failed "+file.getAbsolutePath(), e);
		}
		finally {
			if (null != reader) {
				reader.close();
				reader = null;
			}
		}
	}

	/* (non-Javadoc)
	 * @see name.yzhu.common.util.IdentifyUnique#close()
	 */
	@Override
	public void close() throws Exception {
	}

	/* (non-Javadoc)
	 * @see name.yzhu.common.util.IdentifyUnique#put(java.lang.Object, java.lang.Object)
	 */
	@Override
	public void put(Object key, Object value) throws Exception {
		put(String.valueOf(key), value);
	}

	/* (non-Javadoc)
	 * @see name.yzhu.common.util.IdentifyUnique#put(java.lang.String, java.lang.Object)
	 */
	@Override
	public void put(String key, Object value) throws Exception {
		map.put(key, value);
	}

	/* (non-Javadoc)
	 * @see name.yzhu.common.util.IdentifyUnique#get(java.lang.Object)
	 */
	@Override
	public Object get(Object key) throws Exception {
		return map.get(key);
	}

	/* (non-Javadoc)
	 * @see name.yzhu.common.util.IdentifyUnique#get(java.lang.String)
	 */
	@Override
	public Object get(String key) throws Exception {
		return map.get(key);
	}

	/* (non-Javadoc)
	 * @see name.yzhu.common.util.IdentifyUnique#contain(java.lang.String)
	 */
	@Override
	public boolean contain(String key) throws Exception {
		return map.containsKey(key);
	}

	/* (non-Javadoc)
	 * @see name.yzhu.common.util.IdentifyUnique#contain(java.lang.Object)
	 */
	@Override
	public boolean contain(Object key) throws Exception {
		return map.containsKey(key);
	}
}
